
from functools import wraps

from app.api_v1.models import User
from sanic import json

def login_required(func):
    @wraps(func)
    def wrapper(request, *args, **kwargs):
        # query user password
        # session get user id
        user = User.get_or_none(name=request.ctx.session.get('username'))
        if None == user:
            # abort(403)
            return json({'status':'fail', 'message':'请先登录帐号ssss'}, 403)
        results = func(*args, **kwargs)
        return results
    return wrapper

def permission_required(permission):
    def decorator(func):
        @wraps(func)
        def wrapper(request, *args, **kwargs):
            # query user password
            # session get user id
            print('start x' * 30)
            user = User.get_or_none(name=request.ctx.session.get('username'))
            if None == user:
                return json({ 'status':'fail', 'message':'请先登录帐号ssss'}, 403)
            else:
                has_permission = permission in user.auths
                if None == has_permission:
                    return json( {'status':'fail', 'message':f'没有{permission}权限'}, 404)
                else:
                    return json( {'status':'fail', 'message':f'当前用户 {user.auths} 权限'}, 404)
            print(f'user {user}.')
            print('end x' * 30)
            results = func(request, *args, **kwargs)
            return results
        return wrapper
    return decorator